import os
import yaml
from core.models import PersonaConfig, BasePersonaConfig, ExtendedPersonaConfig
from dotenv import load_dotenv
from typing import List, Union
from config.config import Config

load_dotenv()


class PersonaRepository:
    def __init__(self, config_path: str = None):
        self.config_path = config_path or Config.data["PERSONAE_DIR"]

    def load_persona(self, persona_name: str) -> PersonaConfig:
        """加载并验证人格配置"""
        file_path = os.path.join(self.config_path, f"{persona_name}.yaml")
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"Persona config {persona_name} not found")

        with open(file_path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
            return PersonaConfig.from_dict(data).config

    def list_available_personae(self) -> List[str]:
        """获取所有可用人格"""
        return [
            f.split(".")[0]
            for f in os.listdir(self.config_path)
            if f.endswith(".yaml") and not f.endswith("legacy.yaml")
        ]

    def get_persona_type(self, persona_name: str) -> str:
        """获取人格类型"""
        persona = self.load_persona(persona_name)
        return "base" if persona.is_based else "extended"


class PersonaManager:
    def __init__(self, repo: PersonaRepository = None):
        self.repo = repo or PersonaRepository()
        self.current_persona = "professional"  # 默认人格

    def switch_persona(
        self, persona_name: str
    ) -> Union[BasePersonaConfig, ExtendedPersonaConfig]:
        """切换当前人格"""
        if persona_name not in self.repo.list_available_personae():
            # raise ValueError(f"Invalid persona: {persona_name}")
            return None

        self.current_persona = persona_name
        return self.get_current_persona()

    def get_current_persona(self) -> Union[BasePersonaConfig, ExtendedPersonaConfig]:
        """获取当前人格配置"""
        return self.repo.load_persona(self.current_persona)

    def is_base_persona(self) -> bool:
        """检查当前人格是否为基础人格"""
        return self.get_current_persona().is_based

    def get_persona_details(self) -> dict:
        """获取格式化的人格详情"""
        persona = self.get_current_persona()
        details = {
            "name": persona.name,
            "type": "基础人格" if persona.is_based else "扩展人格",
            "description": f"{persona.existing_form} - {persona.portrait}",
            "style": f"{persona.character} | {persona.talking_style}",
        }

        if not persona.is_based:
            extended = persona  # 类型转换为ExtendedPersonaConfig
            details["expertise"] = extended.background_knowledge.get(
                "knowledge_domain", {}
            ).get("professional_expertise", "")
            details["special_abilities"] = list(
                extended.function_interaction.get("core_function_modules", {}).keys()
            )

        return details
